﻿/*
 *  Copyright 2015 Vitaliy Fedorchenko (nrecosite.com)
 *
 *  Licensed under PivotData Source Code Licence (see LICENSE file).
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 
 *  OF ANY KIND, either express or implied.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.IO;
using System.Net;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Data;

using System.Web.Security;

using NReco.PivotData;

namespace Controllers {
	
	public class PivotController : Controller {

		public ActionResult DemoPage() {
			return View();
		}

		public ActionResult PivotTable() {
			var pvtData = GetDataCube();
			
			// slice data cube with CopyTo method
			// more convinient and efficient way: SliceQuery from PivotData Toolkit
			var slicedPvtData = new PivotData(
					new[]{"funded_year_quarter","category"},
					new SumAggregatorFactory("raisedAmt"), true);

			var filterByCategories = new [] {"web","software","hardware"};
			pvtData.CopyTo(slicedPvtData,
				 (key, aggr) => { 
					// lets filter by category
					if (!filterByCategories.Contains( key[1].ToString() ) )
						return null;
					return new[]{ key[3], key[1] }; 
				 },
				 (aggr) => { return ((CompositeAggregator)aggr).Aggregators[1]; }
			);

			// illustrates how to build classic 2D pivot table
			var pvtTbl = new PivotTable(
					new [] {"funded_year_quarter"}, // rows
					new [] {"category"},
					slicedPvtData);
			
			return PartialView(pvtTbl);
		}

		public ActionResult GoogleChart() {
			var pvtData = GetDataCube();

			return PartialView(pvtData);
		}

		public PivotData GetDataCube() {
			// load serialized cube from sample file (aggregation result of 'TechCrunchcontinentalUSA.csv' from CsvDemo example) 
			var cubeFile = HttpContext.Server.MapPath("~/App_Data/TechCrunchCube.dat");
			
			// configuration of the serialized cube
			var pvtData = new PivotData(new[]{"company","category","fundedDate","funded_year_quarter","round"},
					new CompositeAggregatorFactory( 
						new CountAggregatorFactory(),
						new SumAggregatorFactory("raisedAmt"),
						new AverageAggregatorFactory("raisedAmt"),
						new MaxAggregatorFactory("raisedAmt")
					), false);
			using (var fs = new FileStream(cubeFile, FileMode.Open)) {
				var pvtState = PivotDataState.Deserialize(fs);
				pvtData.SetState(pvtState);
			}
			return pvtData;
		}



	}
}
